package com.tedu.redissample.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.redissample.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisController {
    //pom.xml中添加redis依赖，框架会自动创建stringRedisTemplate对象，放在spring容器中
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/select")
    public Item select() throws  Exception{
        String string = stringRedisTemplate.opsForValue().get("item9000");
        ObjectMapper objectMapper=new ObjectMapper();
        Item item=objectMapper.readValue(string,Item.class);
        return item;
    }

    @RequestMapping("/insert")
    public String insert()  throws Exception {
        //1,创建商品
        Item item =new Item("item9000","mate10");
        //2,把对象转成字符串
        ObjectMapper objectMapper=new ObjectMapper();
        String string = objectMapper.writeValueAsString(item);
        //3,把字符串保存到redis中
        stringRedisTemplate.opsForValue().set("item9000",string);
        return "insert ok";
    }
}
